package org.xxpay.pay.channel.xx2pay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.PayDigestUtil;
import org.xxpay.core.entity.TransOrder;
import org.xxpay.pay.channel.BaseTransNotify;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class Xx2payTransNotifyService extends BaseTransNotify {

    private static final MyLog _log = MyLog.getLog(Xx2payTransNotifyService.class);

//    @Autowired
//    private BaseNotify4UpdateBalance baseNotify4UpdateBalance;

    @Override
    public String getChannelName() {
        return Xx2payConfig.CHANNEL_NAME;
    }

    /**
     * 解析支付宝回调请求的数据
     * @param request
     * @return
     */
    private Map buildNotifyData(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        return params;
    }


    @Override
    public String doNotify(Object notifyData) {
        String logPrefix = "【处理xx2pay代付回调】";
        _log.info("====== 开始处理xx2pay代付回调通知 ======");
        JSONObject retObj = buildRetObj();
        HttpServletRequest req = (HttpServletRequest) notifyData;

        JSONObject paramJSON = new JSONObject(buildNotifyData(req));

        String mchOrderNo = paramJSON.getString("mchOrderNo");
        if(StringUtils.isEmpty(mchOrderNo)){
            return buildRet("订单号不存在！");
        }

        TransOrder transOrder = commonService.transOrderService.findByTransOrderId(mchOrderNo);
        if (transOrder == null) {
            _log.error("[{}transOrderId={}, db中无此订单", getChannelName(), mchOrderNo);
            return buildRet("db中无此订单！");
        }

        Xx2payConfig xx2payConfig = new Xx2payConfig(getTransParam(transOrder));

        //验签
        String apiSign = paramJSON.getString("sign");
        paramJSON.remove("sign");
        String genSign = PayDigestUtil.getSign(paramJSON, xx2payConfig.getKey());
        if(!apiSign.equalsIgnoreCase(genSign)){

            _log.error("[{}transOrderId={}, 验签失败！", getChannelName());
            return buildRet("验签失败！");
        }

        try {
            String status = paramJSON.getString("status");
            String transMsg = paramJSON.getString("transMsg");
            // 处理订单
            byte transStatus = transOrder.getStatus(); // 转账状态: 0-订单生成,1-转账中,2-转账成功,3-转账失败,4-业务处理完成
//            baseNotify4UpdateBalance.doNotify(transOrder.getPassageAccountId()); //更新上游账户余额
            if(transStatus == PayConstant.TRANS_STATUS_INIT || transStatus == PayConstant.TRANS_STATUS_TRANING) {   // 只有转账状态为初始或处理中时再处理
                // 交易状态:失败/成功/已退票
                if("2".equals(status)) {   // 确认成功
                    _log.info("{} >>> 转账成功", logPrefix);

                    boolean updateRows = updateConfirmSuccess(transOrder, null);
                    if (!updateRows) {
                        _log.info("{}更新转账状态失败,将transOrderId={},更新transStatus={}失败", logPrefix, transOrder.getTransOrderId(), PayConstant.TRANS_STATUS_SUCCESS);
                        return buildRet("处理订单失败");
                    }
                    _log.info("{}更新转账状态成功,将transOrderId={},更新transStatus={}成功", logPrefix, transOrder.getTransOrderId(), PayConstant.TRANS_STATUS_SUCCESS);
                    transOrder.setStatus(PayConstant.TRANS_STATUS_SUCCESS);
                }else if("3".equals(status)){ // 确认失败
                    _log.info("{} >>> 转账失败", logPrefix);

                    boolean updateRows = updateConfirmFail(transOrder, null,"", transMsg);

                    if (!updateRows) {
                        _log.info("{}更新转账状态失败,将transOrderId={},更新transStatus={}失败", logPrefix, transOrder.getTransOrderId(), PayConstant.TRANS_STATUS_FAIL);
                        return buildRet("处理订单失败");
                    }
                    _log.info("{}更新转账状态成功,将transOrderId={},更新transStatus={}成功", logPrefix, transOrder.getTransOrderId(), PayConstant.TRANS_STATUS_FAIL);
                    transOrder.setStatus(PayConstant.TRANS_STATUS_FAIL);
                }
            }
            _log.info("====== 完成处理xx2pay代付回调通知 ======");
            return buildRet("SUCCESS");

        } catch (Exception e) {
            _log.error(e, logPrefix + "处理异常");
            return buildRet(e.getMessage());
        }

    }

    /**
     * 生成回调同步响应数据
     * @param msg
     * @return
     */
    String buildRet(String msg) {
        return msg;
    }
}
